package com.winit;

import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

@SpringBootApplication(scanBasePackages = "com.winit")
@EnableCaching
public class Application {
    private static Logger logger = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    /**
     * 设置缓存超时时间，由于spring cache没有提供expire time api，
     * 所以各种cache implementation 的expire time设置并不相同
     * @param cacheManager
     * @return
     */
    @Bean
    @SuppressWarnings("all")
    public Object configCache(CacheManager cacheManager){
        try {
            Field field = GuavaCacheManager.class.getDeclaredField("cacheBuilder");
            field.setAccessible(true);
            //设置120分钟expire time
            ((CacheBuilder)(field.get(cacheManager))).expireAfterWrite(120l, TimeUnit.MINUTES);
        } catch (Exception e) {
            logger.info("cache evict time setter failed.");
            logger.info(e.getMessage(), e);
        }
        return null;
    }
}
